<template>
    <el-tree ref="treeRef" :data="depList" show-checkbox node-key="id" :props="defaultProps"
        @check-change="handleTreeCheck" />
</template>
<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { getDepartmentlist } from '@/api/cf'

interface Tree {
    id: number;
    name: string;
    children?: Tree[];
}

const defaultProps = {
    children: 'children',
    label: 'name',
}
const treeRef = ref()
const depList = ref([])

const emit = defineEmits(['tree-check'])

const getDepList = async () => {
    await getDepartmentlist('').then((res) => {
        depList.value = res.data
    })
}

const getChecked = () => {
    return {
        // 全选节点（不包含半选）
        fullChecked: treeRef.value?.getCheckedNodes() || [],
        // 全选节点ID
        fullCheckedKeys: treeRef.value?.getCheckedKeys() || [],
        // 包含半选节点
        halfChecked: treeRef.value?.getHalfCheckedNodes() || [],
        halfCheckedKeys: treeRef.value?.getHalfCheckedKeys() || []
    }
}

const handleTreeCheck = () => {
    const selectedDepartments = getChecked().fullChecked
    const selectedDepartmentsIds = selectedDepartments.map((n: Tree) => n.id)
    emit('tree-check', selectedDepartmentsIds)
}

onMounted(async () => {
    await getDepList()
})
</script>